package com.lighting.common.dubbo.filter;

import com.lighting.common.core.vo.BusinessException;
import com.lighting.common.core.vo.RpcException;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.service.GenericService;

/**
 * @author lighting
 * 自定义异常过滤器，让dubbo放行自定义异常， order改为大于0，后于ExceptionFilter执行
 */
@Activate(group = CommonConstants.PROVIDER, order = 1)
public class ExceptionFilter extends org.apache.dubbo.rpc.filter.ExceptionFilter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws org.apache.dubbo.rpc.RpcException {
        Result result = invoker.invoke(invocation);
        if (!result.hasException() || GenericService.class == invoker.getInterface()) {
            return result;
        }
        // 偷梁换柱，将BusinessException换为RpcException，以便在ExceptionFilter中放行
        if (result.getException() instanceof BusinessException) {
            result.setException(new RpcException((BusinessException) result.getException()));
        }
        return result;
    }
}

